package com.doodle.common.utils;

import android.graphics.Bitmap;
import android.graphics.Rect;

public class SfbEngine {

	protected static final long HANDLE_INVALID = 0x0;
	protected long mHandle = HANDLE_INVALID;
	protected Bitmap mBitmap = null;
	protected SfbFace[] mFaces = null;
	protected int mFaceCnt = 0;

	public static native long nativeCreate(Bitmap bitmap, int width, int height);
	public static native int nativeDetectFaces(long handle);
	public static native int nativeGetFaceByIndex(long handle, int faceIndex, SfbFace face);

	public static native void nativeDestroy(long handle);

	protected SfbEngine(Bitmap bitmap) {
		mBitmap = bitmap;
		if (mBitmap != null) {
			mHandle = nativeCreate(mBitmap, mBitmap.getWidth(),
					mBitmap.getHeight());
		}
	}

	public static SfbEngine create(Bitmap bitmap) {

		return new SfbEngine(bitmap);
	}

	public int detectFace() {
		mFaceCnt = 0;
		if (mHandle != HANDLE_INVALID) {
			mFaceCnt = nativeDetectFaces(mHandle);
			if (mFaceCnt > 0) {
				mFaces = new SfbFace[mFaceCnt];
				for (int i = 0; i < mFaceCnt; i++) {
					mFaces[i] = new SfbFace();
					nativeGetFaceByIndex(mHandle, i, mFaces[i]);
				}
			}
		}
		return mFaceCnt;
	}

	public int getFaceCount() {
		return mFaceCnt;
	}

	public SfbFace[] getFaces() {
		return mFaces;
	}

	public SfbFace getFaceByIndex(int index) {
		if (mFaces != null && index >= 0 && index < mFaceCnt) {
			return mFaces[index];
		}
		return null;
	}

	public void destroy() {
		if (mHandle != HANDLE_INVALID) {
			nativeDestroy(mHandle);
			mHandle = HANDLE_INVALID;
		}
	}
	
	public static Rect getFacesRect(Bitmap bitmap) {
		Rect rect = new Rect();
		 rect.setEmpty();
		SfbEngine engine = SfbEngine.create(bitmap);
		if (engine != null) {
			int faceCount = engine.detectFace();
			if (faceCount > 0) {
				for (int i = 0; i < faceCount; i++) {
					SfbFace face = engine.getFaceByIndex(i);
					GTRect faceRect = face.getFaceRectangle();
					 rect.union(faceRect.left, faceRect.top, faceRect.left + faceRect.width, faceRect.top + faceRect.height);
				}
			}
			engine.destroy();
		}
		return rect;
	}

	static {
		System.loadLibrary("Face");
	}
}
